﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using ElingOA6_Admin_DSJCJ.Models;
using System.Data;
using System.IO;
using DevExpress.Web.Mvc;
using System.Text.RegularExpressions;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 软件管理
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class SoftwareEntryController : AdminBaseController
    {
        //
        // GET: /Admin/SoftwareEntry/

        /// <summary>
        /// 软件管理
        /// </summary>
        /// <returns>返回软件管理主页面视图</returns>
        [AuthorityActionFilter("m_SoftWare", Order = 1)]
        [LogPageActionFilter("软件管理", Order = 2)]
        #region 视图
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 构造软件管理树
        /// </summary>
        /// <returns>返回软件管理树视图</returns>
        public ActionResult SoftwareEntryTree()
        {
            BLL.SoftwareCatalog softwareCatalogBll = new BLL.SoftwareCatalog();
            TreeModelList treeModelList = new TreeModelList();

            List<Model.SoftwareCatalog> allList = softwareCatalogBll.GetModelListByFEntityNo(GlobalConstant.ENTITYNO);

            if (allList.Count > 0)
            {
                List<Model.SoftwareCatalog> modelList = (from c in allList where c.FPreSoftwareCatalogID == null orderby c.FPreSoftwareCatalogID select c).ToList();

                foreach (Model.SoftwareCatalog model in modelList)
                {
                    TreeItemModel treeParentItemModel = new TreeItemModel(null)
                    {
                        Id = model.FSoftwareCatalogID.ToString(),
                        Name = model.FSoftwareCatalogName,
                        ImageUrl = Url.Content("~/Content/ControlImages/dept_Groups.png")
                    };

                    List<Model.SoftwareCatalog> childModelList = (from c in allList where c.FPreSoftwareCatalogID == model.FSoftwareCatalogID orderby c.FSoftwareCatalogID select c).ToList();
                    if (childModelList.Count > 0)
                    {
                        GetChild(childModelList, treeParentItemModel, allList);
                    }

                    treeModelList.Add(treeParentItemModel);
                }

            }

            return View(treeModelList);
        }

        /// <summary>
        /// 递归获取子节点
        /// </summary>
        /// <param name="modelList">当前父节点下的数据</param>
        /// <param name="treeParentItemModel">父节点</param>
        /// <param name="AllList">全部数据</param>
        private void GetChild(List<Model.SoftwareCatalog> modelList, TreeItemModel treeParentItemModel, List<Model.SoftwareCatalog> allList)
        {
            foreach (Model.SoftwareCatalog model in modelList)
            {

                TreeItemModel treeChildItemModel = new TreeItemModel(treeParentItemModel)
                {
                    Id = model.FSoftwareCatalogID.ToString(),
                    Name = model.FSoftwareCatalogName,
                    ImageUrl = Url.Content("~/Content/ControlImages/dept_Groups.png")
                };

                List<Model.SoftwareCatalog> childModelList = (from c in allList where c.FPreSoftwareCatalogID == model.FSoftwareCatalogID orderby c.FSoftwareCatalogID select c).ToList();

                if (childModelList.Count > 0)
                {
                    GetChild(childModelList, treeChildItemModel, allList);
                }

            }

        }
        /// <summary>
        /// 软件管理
        /// </summary>
        /// <returns>产生软件管理视图</returns>
        public ActionResult SoftwareEntryContent(decimal? catalogID)
        {
            int pageIndex = 1;

            List<Model.SoftwareEntry> EntryList = GetEntryList(catalogID,pageIndex);

            ViewData["catalogID"] = catalogID;
            return View(EntryList);
        }

        /// <summary>
        /// 软件管理列表
        /// </summary>
        /// <returns>返回软件管理列表Grid操作后视图</returns>
        public ActionResult SoftwareEntryContentPartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();
            decimal? catalogID = decimal.Parse(Request.Params["catalogID"]);

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }


            List<Model.SoftwareEntry> EntryList = GetEntryList(catalogID,pageIndex);


            return PartialView("SoftwareEntryContentPartial", EntryList);
        }




        /// <summary>
        /// 增加或者编辑软件
        /// </summary>
        /// <returns>返回增加或者编辑软件视图</returns>
        public ActionResult SoftwareEntryEdit(string addType, decimal? catalogID, decimal? entryID)
        {
            BLL.SoftwareEntry entryBll = new BLL.SoftwareEntry();
            Model.SoftwareEntry entryModel = new Model.SoftwareEntry();
            switch (addType)
            {
                case "ADD":
                    entryModel.FPubEmpNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                    entryModel.FPubDate = DateTime.Now;
                    ViewData["catalogID"] = catalogID;
                    break;
                case "EDIT":
                    entryModel = entryBll.GetModel(entryID.Value);

                    ViewData["entryID"] = entryID;
                    ViewData["SvrFileName"] = entryModel.FSoftwareSvrFileName;
                    ViewData["Size"] = entryModel.FSize;
                    ViewData["OldFileName"] = entryModel.FAttachOldFileName;

                    ViewData["catalogID"] = entryModel.FSoftwareCatalogID;
                    break;
            }

            BLL.HREmpl hrEmplBll=new BLL.HREmpl();
            ViewData["emplName"] = hrEmplBll.GetEmpName(GlobalConstant.ENTITYNO,entryModel.FPubEmpNo);
            ViewData["addType"] = addType;
            
            return View(entryModel);
        }

        public ActionResult SoftwareEntryUpload(decimal catalogID)
        {
            string upload_url = Url.Content("~/Admin/SoftwareEntry/SoftwareEntrySave?catalogID=" + catalogID);
            string file_size_limit = "2147483648";
            string file_types = "*.exe;*.iso;*.rar;*.msi;*.zip";
            string DesTitle = "上传软件（支持的软件类型exe,iso,rar,msi,zip)";
            string button_image_url = Url.Content("~/Content/images/XPButtonUploadText_61x22.png");

            ViewData["button_image_url"] = button_image_url;
            ViewData["DesTitle"] = DesTitle;
            ViewData["file_types"] = file_types;
            ViewData["file_size_limit"] = file_size_limit;
            ViewData["upload_url"] = upload_url;

            return View();
        }

        public ActionResult SoftwareEntrySave(decimal catalogID)
        {
            Response.Expires = 0;
            try
            {
                System.Web.HttpFileCollectionBase uploadFiles = Request.Files;
                HttpPostedFileBase theFile;
                if (uploadFiles.Count > 0)
                {
                    for (int i = 0; i < uploadFiles.Count; i++)
                    {
                        theFile = uploadFiles[i];
                        if (theFile != null)
                        {
                            //文件后缀名
                            string _backname = theFile.FileName.Substring(theFile.FileName.LastIndexOf('.') + 1);
                            //公司编号
                            string _entityNo =GlobalConstant.ENTITYNO;
                            //软件类别编号
                            decimal _softcataid = catalogID;
                            //软件类别名称
                            //string _softCataName=SoftCataBll.getSoftCataName(_softcataid);
                            //目标文件夹
                            string dest_dir = Url.Content("~") + "Publish/" + _entityNo + "/software/" + _softcataid + "/";
                            //服务器文件名
                            string _SvrFileName = GenerateUtil.GenerateStringId();
                            //软件大小
                            decimal size1 = theFile.ContentLength / 1048576;
                            decimal size2 = theFile.ContentLength % 1048576;
                            decimal _size = decimal.Parse(size1.ToString() + "." + size2.ToString().Substring(0, 3));
                            //原来文件名
                            string _oldfilename = theFile.FileName.Substring(theFile.FileName.LastIndexOf('\\') + 1);

                            string uploadoffiepath = Server.MapPath(dest_dir);//上传文件的路径
                            if (!Directory.Exists(uploadoffiepath))//如果不存在就创建
                            {
                                Directory.CreateDirectory(uploadoffiepath);
                            }

                            theFile.SaveAs(uploadoffiepath + _SvrFileName + "." + _backname);
                            Response.Write("successed|" + dest_dir + _SvrFileName + "." + _backname + "," + _size + "," + _oldfilename);
                            Response.Flush();
                            Response.End();


                        }
                    }
                }
            }
            catch
            {

            }
            return View("SoftwareEntryUpload");
        }
        #endregion

        #region AJAX
        //删除软件
        public string DeleteSoft(string Svrfilename)
        {
            string returnValue = "";

            if ("" != Svrfilename)
            {
                try
                {
                    Svrfilename = "~" + Svrfilename;
                    GenerateUtil.DeleteFile(Svrfilename);
                    returnValue = "success";
                }
                catch
                {
                    returnValue = "error";
                }
            }

            return returnValue;
        }

        /// <summary>
        /// 保存软件
        /// </summary>
        /// <param name="softwareName">软件名称</param>
        /// <param name="platform">使用平台</param>
        /// <param name="developer">开发商</param>
        /// <param name="pubEmpNo">发布人</param>
        /// <param name="pubDate">发布日期</param>
        /// <param name="note">软件简介</param>
        /// <returns>返回保存结果</returns>
        [ValidateInput(false)]
        public ActionResult EntrySave()
        {
            BLL.SoftwareEntry entryBll = new BLL.SoftwareEntry();
            Model.SoftwareEntry softwareEntryObject = new Model.SoftwareEntry();
            string addType = Fetch.Post("hidAddType");
            try
            {
                //获取数据
                if (Fetch.Post("hidCatalogID") != "")
                {
                    softwareEntryObject.FSoftwareCatalogID = decimal.Parse(Fetch.Post("hidCatalogID"));
                }
                softwareEntryObject.FSoftwareName = Fetch.Post("FSoftwareName").Trim();
                softwareEntryObject.FPlatform = Fetch.Post("FPlatform").Trim();
                softwareEntryObject.FDeveloper = Fetch.Post("FDeveloper").Trim();
                softwareEntryObject.FPubEmpNo = Fetch.Post("hidPubEmpNo").Trim();
                softwareEntryObject.FPubDate = DateTime.Parse(Fetch.Post("FPubDate"));
                softwareEntryObject.FNote = Request.Form["FNote"].Trim();
                string oldFileName = Fetch.Post("hidOldFileName");
                softwareEntryObject.FAttachFileExt = oldFileName.Substring(oldFileName.LastIndexOf('.') + 1);
                softwareEntryObject.FAttachOldFileName = oldFileName;
                softwareEntryObject.FSoftwareSvrFileName = Fetch.Post("hidSvrFileName");
                softwareEntryObject.FPubIp = Common.GenerateUtil.GetClientIPv4Address();
                softwareEntryObject.FEntityNo = GlobalConstant.ENTITYNO;
                if (Fetch.Post("hidSize") != "")
                {
                    softwareEntryObject.FSize = decimal.Parse(Fetch.Post("hidSize"));
                }

                switch (addType)
                {
                    case "ADD":
                        softwareEntryObject.FDownloadCount = 0;//增加才有
                        entryBll.Add(softwareEntryObject);
                        break;
                    case "EDIT":
                        if (Fetch.Post("hidEntryID") != "")
                        {
                            softwareEntryObject.FSoftwareEntryID = decimal.Parse(Fetch.Post("hidEntryID"));
                        }
                        entryBll.Update(softwareEntryObject);
                        break;
                }
                ViewData["jsAlert"] = "保存成功！";
            }
            catch
            {
                ViewData["jsAlert"] = "保存失败！";
            }

            ViewData["entryID"] = softwareEntryObject.FSoftwareEntryID;
            ViewData["SvrFileName"] = softwareEntryObject.FSoftwareSvrFileName;
            ViewData["Size"] = softwareEntryObject.FSize;
            ViewData["OldFileName"] = softwareEntryObject.FAttachOldFileName;
            ViewData["catalogID"] = softwareEntryObject.FSoftwareCatalogID;
            BLL.HREmpl hrEmplBll=new BLL.HREmpl();
            ViewData["emplName"] = hrEmplBll.GetEmpName(GlobalConstant.ENTITYNO, softwareEntryObject.FPubEmpNo);
            ViewData["addType"] = addType;
            
            return View("SoftwareEntryEdit",softwareEntryObject);
        }

        /// <summary>
        /// 删除功能
        /// </summary>
        /// <param name="entryID">软件编号</param>
        /// <returns>返回删除结果</returns>
        public string DelEntry(decimal entryID)
        {
            string returnValue = "";
            BLL.SoftwareEntry entryBll = new BLL.SoftwareEntry();
            try
            {
                Model.SoftwareEntry entryModel =entryBll.GetModel(entryID);
                if (entryModel.FSoftwareSvrFileName != null)
                {
                    if (entryModel.FSoftwareSvrFileName.Trim() != "")
                    {
                        if ("success" == DeleteSoft(entryModel.FSoftwareSvrFileName))
                        {
                            entryBll.Delete(entryID);
                            returnValue = "success";
                        }
                        else
                        {
                            returnValue = "softDelError";
                        }
                    }
                    else
                    {
                        entryBll.Delete(entryID);
                        returnValue = "success";
                    }
                }
                else
                {
                    entryBll.Delete(entryID);
                    returnValue = "success";
                }
            }
            catch
            {
                returnValue = "error";
            }

            return returnValue;
        }


        public string DelManyEntry(string entryIDArray)
        {
            string returnValue = "";
            try
            {
                string[] entryIDList = entryIDArray.Split(new string[] { "%!^" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string strEntryID in entryIDList)
                {
                    decimal entryID = decimal.Parse(strEntryID);
                    DelEntry(entryID);
                }
                returnValue = "success";
            }
            catch
            {
                returnValue = "error";
            }
            return returnValue;

        }



        #endregion

        #region 私有方法
        /// <summary>
        /// 获取工作组集合
        /// </summary>
        /// <param name="pageIndex">页数</param>
        /// <param name="pageRowSize">每页显示条数</param>
        /// <returns>工作组集合</returns>
        private List<Model.SoftwareEntry> GetEntryList(decimal? catalogID, int pageIndex, int pageRowSize = 0)
        {
            BLL.Common commonBll = new BLL.Common();
            string fiedls = "*";
            int total;
            string strWhere = "";
            if (catalogID != null)
            {
                strWhere += " FSoftwareCatalogID=" + catalogID;
            }
            DataSet ds = commonBll.GetListByPage("t_SoftwareEntry", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, strWhere, "FSoftwareEntryID", 0, out total);

            BLL.SoftwareEntry entryBll = new BLL.SoftwareEntry();
            List<Model.SoftwareEntry> AllList = new List<Model.SoftwareEntry>();
            List<Model.SoftwareEntry> ModelList = entryBll.DataTableToList(ds.Tables[0]);
            pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                AllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (ModelList.Count > i)
                {
                    AllList[((pageIndex - 1) * pageRowSize) + i] = ModelList[i];
                }
            }

            return AllList;
        }

        #endregion
    }
}
